<?php

namespace frontend\modules\trade\models;

use Yii;
use common\models\shop\ShopOrder;

/**
 * 业务订单模型
 * BizOrderModel use to bizorder payment model.
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class BizOrderModel extends \common\base\Model {

    use \common\traits\Constants;

    /**
     * @var string 支付范围
     */
    const SCOPE_SHOP = 'shop';

    /**
     * @var integer 账号的UID
     */
    public $user_id;

    /**
     * @var string 业务范围名称
     */
    public $scope;

    /**
     * @var integer 业务订单ID
     */
    public $order_id;

    /**
     * @var 业务订单模型
     */
    private $_model = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['user_id', 'order_id', 'scope'], 'required'],
            [['user_id', 'order_id'], 'integer'],
            ['scope', 'string', 'max' => 30],
            ['scope', 'in', 'range' => self::getAttributeMark('scope')],
            ['order_id', 'validateOrder'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'order_id' => '订单ID',
            'user_id' => '用户ID',
            'paymode' => '支付方式',
            'scope' => '业务类型',
            'partner_id' => '商户ID',
        ];
    }

    /**
     * 校验订单信息
     */
    public function validateOrder($attribute) {
        if (!$this->hasErrors()) {
            $model = $this->getOrderModel($this->scope, $this->order_id);
            if ($model) {
                if ($model->user_id !== $this->user_id) {
                    $this->addError($attribute, '订单信息不正确，非当前用户的订单');
                } else {
                    $this->setModel($model);
                }
            } else {
                $this->addError($attribute, '订单超时或者订单状态已变更');
            }
        }
    }

    /**
     * @return \api\models\UserCompatibleModel|null
     */
    protected function getOrderModel($type, $id) {
        if (!method_exists($this, $type)) {
            return null;
        }
        return $this->{$type}($id);
    }

    /**
     * @inheritdoc
     */
    protected function shop($id) {
        $model = ShopOrder::findOne([
            'id' => $id,
            'status' => [ShopOrder::STATUS_DEFAULT, ShopOrder::STATUS_ACTIVE],
        ]);
        if ($model && !$model->getIsExpired()) {
            return $model;
        }
        return null;
    }

    /**
     * @return \api\models\UserCompatibleModel|null
     */
    protected function setModel($model) {
        $this->_model = $model;
    }

    /**
     * @return \api\models\UserCompatibleModel|null
     */
    protected function getModel() {
        return $this->_model;
    }

}
